package com.ljx.funchat.user.service.impl;

import com.ljx.funchat.common.constant.RedisKey;
import com.ljx.funchat.common.utils.JwtUtils;
import com.ljx.funchat.common.utils.RedisUtils;
import com.ljx.funchat.user.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.concurrent.TimeUnit;


@Service
public class LoginServiceImpl implements LoginService {

    public static final int TOKEN_EXPIRE_TIME = 3;

    @Autowired
    private JwtUtils jwtUtils;

    @Override
    public String login(Long uid) {
        String token = jwtUtils.createToken(uid);
        // 保存redis
        RedisUtils.set(getUserTokenKey(uid), token, TOKEN_EXPIRE_TIME, TimeUnit.DAYS);
        return token;
    }

    private String getUserTokenKey(Long uid) {
        return RedisKey.getKey(RedisKey.USER_TOKEN, uid);
    }

    @Override
    public Long getValidUid(String token) {
        Long uid = jwtUtils.getUidOrNull(token);
        if (Objects.isNull(uid)){
            return null;
        }
        // 检验token是否有效【是否存在一个用户多次登录获取不同token的情况】
        String oldToken = RedisUtils.getStr(getUserTokenKey(uid));
        return Objects.equals(oldToken, token) ? uid : null;
    }
}
